package com.estore.service;

import com.estore.model.Product;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品服务类，负责商品相关的业务逻辑
 */
public class ProductService {

    private final Map<String, Product> productData = new HashMap<>();

    public ProductService() {
        // 初始化商品数据
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
        productData.put("p005", new Product("p005", "Python编程实战", 79.0, 80));
        productData.put("p006", new Product("p006", "数据结构与算法", 120.0, 30));
    }

    /**
     * 获取所有商品列表
     */
    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    /**
     * 根据ID查找商品
     */
    public Product findProductById(String id) {
        return productData.get(id);
    }

    /**
     * 验证商品是否存在
     */
    public boolean isProductExist(String id) {
        return productData.containsKey(id);
    }

    /**
     * 验证库存是否充足
     */
    public boolean isStockSufficient(String id, int quantity) {
        Product product = productData.get(id);
        return product != null && product.getStock() >= quantity;
    }

    /**
     * 减少商品库存
     */
    public void reduceStock(String id, int quantity) {
        Product product = productData.get(id);
        if (product != null) {
            product.setStock(product.getStock() - quantity);
        }
    }
}